package com.commerce.constellation;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.commerce.constellation.adapter.MySpinnerAdapter;
import com.commerce.constellation.entity.Month;
import com.commerce.constellation.entity.TodayTomorrow;
import com.commerce.constellation.entity.Week;
import com.commerce.constellation.entity.Year;
import com.commerce.constellation.tools.RetrofitCall;
import com.commerce.constellation.view.HeartLayout;
import com.google.gson.Gson;
import com.mob.MobSDK;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private Timer mTimer;
    private Random mRandom;
    private TextView mTvInfo;
    private Spinner mSpMnConstellation;
    private RatingBar mRbWhole;
    private RatingBar mRbHealth;
    private RatingBar mRbLove;
    private RatingBar mRbMoney;
    private RatingBar mRbWork;
    private TextView mTvMatching;
    private TextView mTvNumber;
    private TextView mTvColor;
    private HeartLayout mHeartLayout;
    private TextView mTvJob;
    private TextView mTvLove;
    private TextView mTvCareer;
    private TextView mTvMoney;
    private TextView mTvMnInfo;
    private TextView mTvYearInfo;
    private TextView mTvYearJob;
    private TextView mTvYearLove;
    private TextView mTvYearColor;
    private TextView mTvYearMoney;
    private TextView mTvMonthAll;
    private TextView mTvMonthLove;
    private TextView mTvMonthWork;
    private TextView mTvMonthHealth;
    private TextView mTvMonthMoney;
    private View today;
    private View week;
    private View month;
    private View year;
    private String conName;
    private String type;
    private Boolean b = false;
    private static AlertDialog.Builder failedDialog;
    private ScrollView jieTuo;
    private String conent;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

    }

    private void initView() {
        jieTuo = findViewById(R.id.jietuo);
        findViewById(R.id.share).setOnClickListener((v -> getShare()));
        mTvMnInfo = findViewById(R.id.tv_mn_info);
        mHeartLayout = findViewById(R.id.heart_layout);
        mSpMnConstellation = findViewById(R.id.sp_mn_constellation);
        findViewById(R.id.fin).setOnClickListener((v)->finish());
        today = findViewById(R.id.sc_today);
        mTvInfo = findViewById(R.id.tv_info);
        mRbWhole = findViewById(R.id.rb_whole);
        mRbHealth = findViewById(R.id.rb_health);
        mRbLove = findViewById(R.id.rb_love);
        mRbMoney = findViewById(R.id.rb_money);
        mRbWork = findViewById(R.id.rb_work);
        mTvMatching = findViewById(R.id.tv_matching);
        mTvColor = findViewById(R.id.tv_color);
        mTvNumber = findViewById(R.id.tv_number);

        week = findViewById(R.id.sc_week);
        mTvJob = findViewById(R.id.tv_job);
        mTvLove = findViewById(R.id.tv_love);
        mTvCareer = findViewById(R.id.tv_career);
        mTvMoney = findViewById(R.id.tv_money);

        year = findViewById(R.id.sc_year);
        mTvYearInfo = findViewById(R.id.tv_year_info);
        mTvYearColor = findViewById(R.id.tv_year_color);
        mTvYearJob = findViewById(R.id.tv_year_job);
        mTvYearLove = findViewById(R.id.tv_year_love);
        mTvYearMoney = findViewById(R.id.tv_year_money);

        month = findViewById(R.id.sc_month);
        mTvMonthAll = findViewById(R.id.tv_month_all);
        mTvMonthLove = findViewById(R.id.tv_month_love);
        mTvMonthWork = findViewById(R.id.tv_month_work);
        mTvMonthHealth = findViewById(R.id.tv_month_health);
        mTvMonthMoney = findViewById(R.id.tv_month_money);
        //下拉框放数据
        String[] stringName = getResources().getStringArray(R.array.constellation_name);
        TypedArray stringIcon = getResources().obtainTypedArray(R.array.constellation_icon);
        MySpinnerAdapter mySpinnerAdapter = new MySpinnerAdapter(this, stringName, stringIcon);
        mSpMnConstellation.setAdapter(mySpinnerAdapter);
        type =getIntent().getStringExtra("type");
        //下拉框，初始化时运行一次
        mSpMnConstellation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                conName = stringName[(int) id];
                getDesc();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        anim();
    }

    /**
     * 飘心动画特效启动
     */
    private void anim() {
        //开一个定时器
        mTimer = new Timer();
        mRandom = new Random();
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                mHeartLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        mHeartLayout.addHeart(randomColor());
                    }
                });
            }
        }, 500, 300);
    }

    /**
     * 获取星座数据
     */
    private void getDesc() {
        Call<ResponseBody> call = RetrofitCall.getConstellationCall(this, conName, type);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    //判断类型进入对应分析
                    switch (type) {
                        case "today":
                        case "tomorrow":
                            today(string);
                            break;
                        case "week":
                            week(string);
                            break;
                        case "month":
                            month(string);
                            break;
                        case "year":
                            year(string);
                            break;
                        default:
                            showFailedDialog();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                showFailedDialog();
            }
        });
    }

    /**
     * 到达上限时或者无网时对话框
     */
    private void showFailedDialog() {
        failedDialog = new AlertDialog.Builder(MainActivity.this);
        //设置对话框图标
        failedDialog.setIcon(R.drawable.jiangao);
        //设置对话框标题
        failedDialog.setTitle("加载失败");
        //设置对话框消息提示
        failedDialog.setMessage("\n         " + "抱歉数据获取异常");
        failedDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        // 显示
        failedDialog.show();
    }

    /**
     * 本月的星座数据解析
     *
     * @param string json串
     */
    private void month(String string) {
        gone();
        month.setVisibility(View.VISIBLE);
        Month month = new Gson().fromJson(string, Month.class);
        String date = month.getDate();
        mTvMnInfo.setText(date);
        conent = month.getAll();
        mTvMonthAll.setText(conent);
        String love = month.getLove();
        mTvMonthLove.setText(love);
        String work = month.getWork();
        mTvMonthWork.setText(work);
        String health = month.getHealth();
        mTvMonthHealth.setText(health);
        String money = month.getMoney();
        mTvMonthMoney.setText(money);
    }

    /**
     * 今年的星座数据解析
     *
     * @param string json串
     */
    private void year(String string) {
        gone();
        year.setVisibility(View.VISIBLE);
        Year years = new Gson().fromJson(string, Year.class);
        conent = years.getMima().getInfo();
        mTvMnInfo.setText(conent);
        String text = years.getMima().getText().get(0);
        mTvYearInfo.setText(text);
        String career = years.getCareer().get(0);
        mTvYearJob.setText(career);
        String love = years.getLove().get(0);
        mTvYearLove.setText(love);
        String finance = years.getFinance().get(0);
        mTvYearMoney.setText(finance);
        String luckeyStone = years.getLuckeyStone();
        mTvYearColor.setText(luckeyStone);
    }

    /**
     * 本周的星座数据解析
     *
     * @param string json串
     */
    private void week(String string) {
        gone();
        week.setVisibility(View.VISIBLE);
        Week week = new Gson().fromJson(string, Week.class);
        String date = week.getDate();
        mTvMnInfo.setText(date);
        String job = week.getJob();
        mTvJob.setText(job);
        conent = week.getLove();
        mTvLove.setText(conent);
        String work = week.getWork();
        mTvCareer.setText(work);
        String money = week.getMoney();
        mTvMoney.setText(money);
    }

    /**
     * 今天或明天的星座数据解析
     *
     * @param string json串
     */
    private void today(String string) {
        //隐藏今天（明天）、本周、本月、今年的布局
        gone();
        //显示今天的布局
        today.setVisibility(View.VISIBLE);
        //Gson解析存入实体类
        TodayTomorrow todayTomorrow = new Gson().fromJson(string, TodayTomorrow.class);
        String datetime = todayTomorrow.getDatetime();
        mTvMnInfo.setText(datetime);
        conent = todayTomorrow.getSummary();
        int all = Integer.parseInt(todayTomorrow.getAll());
        int health = Integer.parseInt(todayTomorrow.getHealth());
        int love = Integer.parseInt(todayTomorrow.getLove());
        int money = Integer.parseInt(todayTomorrow.getMoney());
        int work = Integer.parseInt(todayTomorrow.getWork());
        String qFriend = todayTomorrow.getQFriend();
        String qColor = todayTomorrow.getColor();
        int number = todayTomorrow.getNumber();
        mTvInfo.setText(conent);
        //设置评级分数
        mRbWhole.setProgress(all / 10);
        mRbHealth.setProgress(health / 10);
        mRbLove.setProgress(love / 10);
        mRbMoney.setProgress(money / 10);
        mRbWork.setProgress(work / 10);
        mTvMatching.setText(qFriend);
        mTvColor.setText(qColor);
        mTvNumber.setText("" + number);
    }

    /**
     * 布局隐藏
     */
    private void gone() {
        today.setVisibility(View.GONE);
        month.setVisibility(View.GONE);
        week.setVisibility(View.GONE);
        year.setVisibility(View.GONE);
    }

    /**
     * 随机色彩
     *
     * @return
     */
    private int randomColor() {
        return Color.rgb(mRandom.nextInt(255), mRandom.nextInt(255),
                mRandom.nextInt(255));
    }
    /**
     * 分享
     */
    private void getShare(){
        OnekeyShare oks = new OnekeyShare();
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle(conName);
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(conent);
        getBitmap();
        oks.setImagePath(Environment.getExternalStorageDirectory().getPath()+"/scrollview.jpg");
        // 启动分享GUI
        oks.show(MobSDK.getContext());
    }
    /**
     * 获取图片
     */
    private Bitmap getBitmap(){
        Bitmap bitmap;
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap( getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels,
                Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        jieTuo.draw(canvas);
        // 测试输出
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/scrollview.jpg");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            if (null != out) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
            }
        } catch (IOException e) {
        }
        return bitmap;
    }

    @Override
    protected void onStop() {
        //移除已有动画
        mHeartLayout.clearTheAnimation();
        super.onStop();
    }
}